package org.example.servicestudent.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.model.manage.bean.Result;
import org.example.model.manage.bean.po.Student;
import org.example.model.manage.bean.vo.PositioningRequest;
import org.example.model.student.bean.Task;
import org.example.servicestudent.service.StudentService;
import org.example.servicestudent.service.TaskService;
import org.example.servicestudent.vo.StudentInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private TaskService taskService;

    @PostMapping("/binding")
    public Result binding(Long studentId, String unionId) {
        if(studentService.getById(studentId) == null)
            return Result.error(10008, "不存在该学号");

        List<Student> list = studentService.getList(new QueryWrapper<Student>().eq("union_id", unionId));
        if(!list.isEmpty()) {
            for(Student s : list) {
                s.setUnionId(null);
                studentService.updateById(s);
            }
        }

        Student stu = studentService.binding(studentId, unionId);
        return Result.success(stu);
    }

    @GetMapping("/info")
    public Result info(String unionId) {
        List<StudentInfoVO> stu = studentService.getStudentInfoWithMajorName(unionId);
        if(stu != null && !stu.isEmpty())  return Result.success(stu);
        return Result.error(10007, "未绑定");
    }

    /**
     * 学生定位接口
     * @param request 定位请求参数
     * @return 定位结果
     */
    @PostMapping("/positioning")
    public Result positioning(@RequestBody PositioningRequest request) {
        if(studentService.positioning(request.getUnionId(), request.getLatitude(), request.getLongitude())) {
            return Result.success("success");
        }
        return Result.error(10001, "不在范围内");
    }

    @GetMapping("/task")
    public Result task(String unionId) {
        List<Student> list = studentService.getList(new QueryWrapper<Student>().eq("union_id", unionId));
        Integer majorId = null;
        if(!list.isEmpty())  majorId = list.get(0).getMajorId();
        if(majorId == null)  return Result.error(10007, "未绑定");
        List<Task> taskList = taskService.getList(majorId);
        return Result.success(taskList);
    }
}
